#include "send_multiple_area.h"
#include "ui_send_multiple_area.h"

#include <QFile>
#include <QMessageBox>
#include <QTextStream>

#include <QFileDialog>
#include <QScrollArea>

#include <QTableWidget>

#include <QTextCodec>

#include <QDesktopServices>

SendMultipleArea::SendMultipleArea(QWidget* parent) : QWidget(parent), ui(new Ui::SendMultipleArea)
{
    ui->setupUi(this);

    this->timer = new QTimer(this);
    timer->stop();
    timer->setTimerType(Qt::PreciseTimer);
    timer->setSingleShot(false); // 循环
    // 定时到了
    connect(timer, &QTimer::timeout, this, &SendMultipleArea::autoSend);
    // 换页后清0 m_currentRow
    connect(ui->tabWidget, &QTabWidget::currentChanged, this, [this]() {
        this->m_currentRow = 0;
    });

    /*创建保存发送数据的文件夹*/
    QString appDirPath = QCoreApplication::applicationDirPath(); // 获取 .exe 所在的目录
    qDebug() << "程序所在目录:" << appDirPath;
    QString dataDirPath = appDirPath + "/multiple_data_files"; // 构造目标文件夹路径
    QDir dataDir(dataDirPath);                                 // 指向保存数据文件夹的 QDir 对象
    if (dataDir.exists())
    {
        qDebug() << "文件夹:" << dataDirPath << "已存在";
    }
    else
    {
        qDebug() << "文件夹:" << dataDirPath << "原本不存在";
        if (QDir().mkpath(dataDirPath))
        {
            qDebug() << "成功创建文件夹:" << dataDirPath;
        }
        else
        {
            qWarning() << "创建文件夹" << dataDirPath << "失败!";
        }
    }

    // 打开文件保存目录
    connect(ui->pushButton_Location, &QPushButton::clicked, this, [this]() {
        QString location = QCoreApplication::applicationDirPath() + "/multiple_data_files";
        QDir locationDir(location);
        if (!locationDir.exists())
        {
            if (!QDir().mkpath(location))
            {
                qDebug() << "创建失败 " << __FILE__ << __LINE__;
            }
        }

        bool result = QDesktopServices::openUrl(location); // 在资源管理器中打开
        if (!result)
        {
            qDebug() << "无法打开文件夹";
            QMessageBox::warning(this, "提示", "找不到默认保存位置，请检查");
        }
    });

    localEncoding = getLocalEncoding();

    // 导入文件按钮
    connect(ui->pushButton_Import, &QPushButton::clicked, this, [this]() {
        QString fileName = QFileDialog::getOpenFileName(this);
        // 获取选择的编码
        EncodingEnum encoding = static_cast<EncodingEnum>(ui->comboBox_Encoding->currentData().toInt());
        QByteArray encodingName = getEncodingString(encoding);
        if (fileName.isEmpty())
        {
            return;
        }
        ImportFormFile(fileName, encodingName); // 导入文件
    });

    while (ui->tabWidget->count() > 0) // 开始清空tabWidget
    {
        ui->tabWidget->removeTab(0); // 索引会变更
    }

    // 添加编码
    ui->comboBox_Encoding->addItem("UTF-8", EncodingEnum::UTF8);
    ui->comboBox_Encoding->addItem("GB18030", EncodingEnum::GB18030);
    if (localEncoding == EncodingEnum::GB18030)
    {
        int index = ui->comboBox_Encoding->findData(EncodingEnum::GB18030);
        ui->comboBox_Encoding->setCurrentIndex(index);
    }
    else
    {
        int index = ui->comboBox_Encoding->findData(EncodingEnum::UTF8);
        ui->comboBox_Encoding->setCurrentIndex(index);
    }

    // 移除当前页
    connect(ui->pushButton_Delete, &QPushButton::clicked, this, [this]() {
        if (ui->tabWidget->count() <= 0)
        {
            return;
        }
        int index = ui->tabWidget->currentIndex();
        ui->tabWidget->removeTab(index);
    });

    /* 导入 multiple_data_files 中的所有.csv文件 */
    // 获取所有 .csv 文件（不区分大小写）
    QStringList filters;
    filters << "*.csv" << "*.CSV";
    QFileInfoList fileList = dataDir.entryInfoList(filters, QDir::Files); // 只找文件，不找子文件夹
    // 遍历每个 .csv 文件
    for (const QFileInfo& fileInfo : fileList)
    {
        QString filePath = fileInfo.absoluteFilePath(); // 完整路径
        ImportFormFile(filePath, "UTF8");               // 统统认为是 UTF-8编码的
        // qDebug()<<"已导入"<<filePath;
    }
}

SendMultipleArea::~SendMultipleArea()
{
    delete ui;
}

void SendMultipleArea::setSomeComponents(bool checked)
{
    this->portState = checked;
    emit portStateChange(checked);
}

void SendMultipleArea::ImportFormFile(QString fileName, QByteArray encodingName)
{
    QFileInfo fileInfo(fileName);
    QString baseName = fileInfo.baseName(); // 文件名

    // 读取表格文件的数据
    std::vector<std::vector<std::string>> formData = readCSVFile(fileName.toStdString());

    QTableWidget* tableWidget = new QTableWidget(ui->tabWidget); // 表格窗口
    tableWidget->setRowCount(formData.size());
    tableWidget->setColumnCount(3); // 设置为3列
    tableWidget->setHorizontalHeaderLabels(QStringList() << "备注" << "指令" << "发送");

    QVBoxLayout* layout = new QVBoxLayout;
    layout->setContentsMargins(2, 2, 2, 2);
    layout->setSpacing(2);

    layout->addWidget(tableWidget);
    layout->addStretch();

    int lineNumber = 0;

    QTextCodec* codec = QTextCodec::codecForName(encodingName); // 编码转换

    for (int i = 0; i < formData.size(); i++)
    {
        for (int j = 0; j < 2; j++)
        {
            QString temp = codec->toUnicode(formData[i][j].c_str()); // 编码转换
            tableWidget->setItem(i, j, new QTableWidgetItem(temp));
        }
        QPushButton* button = new QPushButton(tableWidget);
        button->setEnabled(portState);
        button->setIcon(QIcon(":/image/image/send.png"));
        connect(button, &QPushButton::clicked, [=]() {
            QString sendData = tableWidget->item(i, 1)->text();
            emit this->requestToSend(sendData);
        });
        connect(this, &SendMultipleArea::portStateChange, button, &QPushButton::setEnabled);

        tableWidget->setCellWidget(i, 2, button);
    }

    ui->tabWidget->addTab(tableWidget, baseName);
    tableWidget->resizeColumnsToContents();
    ui->tabWidget->setCurrentWidget(tableWidget); // 展示新导入的

    qDebug() << "成功从 " << fileName << " 中导入 " + QString::number(formData.size()) + " 条指令";
    // QMessageBox::information(this, "成功", "已导入 " + QString::number(lineNumber) + " 条指令");
}

void SendMultipleArea::autoSend()
{
    if (ui->tabWidget->count() <= 0) // 多页窗口中没有表格
    {
        return;
    }

    // 获取当前表格窗口
    QTableWidget* tableWidget = static_cast<QTableWidget*>(ui->tabWidget->currentWidget());
    if (tableWidget->rowCount() <= 0) // 表格中没有数据
    {
        return;
    }
    // 获取当前行的指令
    QTableWidgetItem* item = tableWidget->item(m_currentRow, 1);
    if (!item)
        return;

    QString command = item->text();
    this->requestToSend(command);

    // //  创建一个选中区域（从 row,col 到 row,col，即单个格子）
    // QItemSelection selection(tableWidget->model()->index(m_currentRow, 1), tableWidget->model()->index(m_currentRow, 1));
    // // 获取 SelectionModel 并设置选中
    // tableWidget->selectionModel()->select(selection, QItemSelectionModel::Select);
    // 设置“当前单元格”（让它显示蓝框焦点）
    tableWidget->setCurrentCell(m_currentRow, 1);

    // 更新行号（下一行）
    m_currentRow++;
    if (m_currentRow >= tableWidget->rowCount())
    {
        m_currentRow = 0; // 回到第一行，实现循环
    }
}

void SendMultipleArea::setAutoSendState(bool checked, int cycle)
{
    if (checked)
    {
        if (this->timer->isActive())
        {
            this->timer->setInterval(cycle);
            qDebug()<<"多项发送区自动发送周期改变";
        }
        else
        {
            this->timer->start(cycle);
            qDebug()<<"多项发送区开始自动发送";
        }
    }
    else
    {
        this->timer->stop();
        qDebug()<<"多项发送区停止自动发送";
    }
}
